﻿using AirIndex.Models.WeiXin;
using HVACWebService.Common;
using HVACWebService.DomainModel.WeiXin;

namespace HVACWebService.Cloud.WeChat
{
    public class WeiXinDevice
    {
        //private string _deviceUnbundWeiXinUrl = "https://api.weixin.qq.com/device/compel_unbind?access_token={0}";

        private readonly string _deviceUnbundWeiXinUrl = ConfigHelper.GetValue<string>("DeviceUnbundWeiXinUrl");

        private readonly string _devicebundWeiXinUrl = ConfigHelper.GetValue<string>("DevicebundWeiXinUrl");

        private readonly string _getDieviceBindOpen = ConfigHelper.GetValue<string>("PhysicalDeviceIdGetOpenId");

        private readonly string _winXinSourceId = ConfigHelper.GetValue<string>("WinXinSourceId");



        public WeiXinShareCodeModel GetShareCode(string physicalDeviceId, string accessToken)
        {
            var shareCodeUrl = ConfigHelper.GetValue<string>("GetShareCodeUrlUrl");
            var httpWebRequestHelp = new HttpWebRequestHelp();
            var url = string.Format(shareCodeUrl, accessToken);
            var data = "{\"device_num\":\"1\",\"device_id_list\":[\"" + physicalDeviceId + "\"]}";
            return httpWebRequestHelp.PostData<WeiXinShareCodeModel>(url, data);
        }



        public bool DeviceUnBind(string openId, string deviceId, string accessToken)
        {
            var httpWebRequestHelp = new HttpWebRequestHelp();
            var url = string.Format(_deviceUnbundWeiXinUrl, accessToken);
           // var data = "{\"device_id\":\"" + deviceId + "\",\"openid\":\"" + "ofRiVw9wGeiuCYOKDcZ66DsikZck" + "\"}";
            var data = "{\"device_id\":\"" + deviceId + "\",\"openid\":\"" + openId + "\"}";

            var postData = httpWebRequestHelp.PostData(url, data);
            return postData.Contains("ok") || postData.Contains("not exist") || postData.Contains("system error") ;
        }

        public bool DeviceBind(string openId, string deviceId, string accessToken)
        {
            var httpWebRequestHelp = new HttpWebRequestHelp();
            var url = string.Format(_devicebundWeiXinUrl, accessToken);
            var data = "{\"device_id\":\"" + deviceId + "\",\"openid\":\"" + openId + "\"}";
            var postData = httpWebRequestHelp.PostData(url, data);
            return postData.Contains("ok") || postData.Contains("not exist");
        }


        public OpenIdList PhysicalDeviceIdGetBindindWeiXinOpenId(string physicalDeviceId, string accessToken)
        {
            var httpWebRequestHelp = new HttpWebRequestHelp();
            var url = string.Format(_getDieviceBindOpen, accessToken, _winXinSourceId, physicalDeviceId);
            var getData = httpWebRequestHelp.GetDataString(url);
            return JsonSerializer.Instance.Deserialize<OpenIdList>(getData);
        }



    }
}